import Toast from 'tdesign-miniprogram/toast/index';
import {OrderStatus} from "../../utils/const.js"
const orderService =  require( '../../services/order/orderService.js');

import {
  getEpochSeconds,
  generateSecureRandomString
} from "../../utils/util.js";

const menuData = [
  [{
      title: '地址',
      tit: '',
      url: '',
      type: 'address',
      funcode: 1
    },
    {
      title: '电话',
      tit: '',
      url: '',
      type: 'phone',
      funcode: 2
    },
    {
      title: '积分',
      tit: '',
      url: '',
      type: 'point',
      funcode: 3
    },
  ],
  [{
      title: '进入管理员后台',
      tit: '',
      url: '',
      type: 'admin-page',
      funcode: 4
    },
    {
      title: '切换上下班',
      tit: '正在营业',
      url: '',
      type: 'admin-page',
      icon: '',
      funcode: 5
    },
    {
      title: '修改营业时间',
      tit: '7:00-13:00',
      url: '',
      type: 'admin-page',
      funcode: 6
    },
    // {
    //   title: '客服热线',
    //   tit: '',
    //   url: '',
    //   type: 'service',
    //   icon: 'service',
    // },
  ],
];

const orderTagInfos = [{
    title: '待付款',
    iconName: 'wallet',
    orderNum: 0,
    tabType: OrderStatus.PENDING_PAYMENT,
    status: 1,
  },
  {
    title: '已付款',
    iconName: 'check-circle',
    orderNum: 0,
    tabType: OrderStatus.PENDING_DELIVERY,
    status: 1,
  },
  {
    title: '退款/售后',
    iconName: 'refresh',
    orderNum: 0,
    tabType: OrderStatus.PENDING_REFUND,
    status: 1,
  },
  {
    title: '待评价',
    iconName: 'chat-message',
    orderNum: 0,
    tabType: OrderStatus.PENDING_COMMENT,
    status: 1,
  },
];

let startWorkTime = null;
let endWorkTime = null;
const getDefaultData = () => ({
  globalData: null,
  shops: null,
  monitorThreadId: '',
  loginData: null,
  showMakePhone: false,
  showTimePicker: false,
  timePickValue: '7:00',
  timePickerTitle: '请选择时间',
  userInfo: {
    avatarUrl: '',
    nickName: '请登录',
    phoneNumber: '',
    address: ''
  },
  menuData,
  orderTagInfos,
  customerServiceInfo: {},
  currAuthStep: 1,
  showKefu: true,
  versionNo: '',
  token: null,
  openid: null,
  code: null,
  prepayArg: '',
  canIUse: wx.canIUse('button.open-type.getUserInfo')
});

var app = getApp();
Page({
  data: getDefaultData(),

  _setWorkTimeForAdmin(startHour=7, startMinute=0, endHour=13, endMinute=0){
    var start = startHour + ':' + (startMinute < 10 ? '0' + startMinute : startMinute);
    var end = endHour + ':' + (endMinute < 10 ? '0' + endMinute : endMinute);
    // 管理员角色
    this.data.menuData[1][2].tit = start + '-' + end;
    this.setData({
      'menuData[1][2].tit': this.data.menuData[1][2].tit
    })
  },

  _setWorkStatusForAdmin(workStatus){
    if (typeof workStatus === 'number' && (workStatus === 1 || workStatus === 0)) {
      workStatus = app._getReasonableWorkStatus(new Date(), workStatus, this.data.shops.shopsDetails[this.data.loginData.shopIdForAdmin]);
      this.setData({
          // 根据 workStatus 的值设置菜单标题
          'menuData[1][1].tit': workStatus === 1 ? '正在营业' : '休息中',
          // 根据 shopIdForAdmin 设置店铺的工作状态
          [`shops.shopsDetails[${this.data.loginData.shopIdForAdmin}].workStatus`]: workStatus
      });
    }
  },

  onLoad() {
    this.getVersionInfo();
    this.setData({
      globalData: app.data.globalData,
      shops: app.data.shops,
      loginData: app.data.loginData
    })
    if(this.data.loginData.shopIdForAdmin){
      const shopId = this.data.loginData.shopIdForAdmin;
      const {startHour, startMinute, endHour, endMinute} = {
        ...this.data.shops.shopsDetails[shopId]
      }
      this._setWorkTimeForAdmin(startHour, startMinute, endHour, endMinute);
    }
    app.data.updataUserPageLoginDataCallback = (() => {
      this.setData({
        loginData: app.data.loginData
      })
    }).bind(this);
    // 查看是否授权
    // wx.getSetting({
    //   success (res){
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
    //       wx.getUserInfo({
    //         success: function(res) {
    //           console.log(res.userInfo)
    //         }
    //       })
    //     }
    //   }
    // })
  },

  bindGetUserInfo(e) {
    wx.getUserInfo({
      success: function (res) {
        console.log(res.userInfo)
      }
    })
    console.log(e.detail.userInfo)
  },

  onShow() {
    this.getTabBar().init();
    this.init();
    let shopId = this.data.loginData.shopIdForAdmin;
    if(shopId){
      let status = this.data.shops.shopsDetails[shopId].workStatus;
      this._setWorkStatusForAdmin(status);
    }
    this.setData({
      loginData: app.data.loginData
    })
    
    var that = this;
    this.data.monitorThreadId = setInterval(()=>{
      that._checkLoginStatus();
    }, 5000);

    if(this.data.loginData.shopIdForAdmin){
      const shopId = this.data.loginData.shopIdForAdmin;
      const {startHour, startMinute, endHour, endMinute} = {
        ...this.data.shops.shopsDetails[shopId]
      }
      this._setWorkTimeForAdmin(startHour, startMinute, endHour, endMinute);
    }
  },

  // _loginCallBack = ((loginData) => {
  //     this.data.loginData = loginData;
  //     this.setData({
  //       loginData: loginData
  //     },()=>{
  //      console.log('app.js中的数据变化，回调到这里来了', this.data.loginData)
  //      if(this.data.loginData.openid){
  //        // 设置进来的数据是登录成功的，隐藏toast
  //        wx.hideToast();
  //      }
  //     })
  //   }).bind(this),
  _loginCallBack(loginData){
    this.data.loginData = loginData;
    this.setData({
      loginData: loginData
    },()=>{
      console.log('app.js中的数据变化，回调到这里来了', this.data.loginData)
      if(this.data.loginData.openid){
        // 设置进来的数据是登录成功的，隐藏toast
        wx.hideToast();
      }
    })
  },

  onPullDownRefresh() {
    console.log('onPullDownRefresh')
    this.init();
  },

  init() {
    // this.fetUseriInfoHandle();
  },

  fetUseriInfoHandle() {
    // this.setData({
    //   userInfo: {
    //     nickName: '正在登录...'
    //   }
    // });
    app._userLogin();
    wx.stopPullDownRefresh();
  },

  onClickCell({currentTarget}) {
    const {funcode} = currentTarget.dataset;
    console.log('----onClickCell------', funcode)
    var that=this;

    switch (funcode) {
      case 4:{
        wx.navigateTo({
          url: '/pages/admin/admin',
        })
        break;
      }
      case 5:{
        console.log('----发送post请求下班休息-----')
        wx.request({
          url: app.data.global_urls.getTriggleWorkStatusUrl(),
          method: 'POST',
          header:{
            'Authorization': `Bearer ${app.data.loginData.token}`,
            'content-type': 'application/x-www-form-urlencoded',
          },
          data:{
            workStatus: this.data.shops.shopsDetails[this.data.loginData.shopIdForAdmin].workStatus
          },
          success(res){
            if(10000 === res.data.status){
              wx.showToast({
                title: '设置成功',
                icon: 'success',
              })
              that._setWorkStatusForAdmin(res.data.data.workStatus)
            }else{
              wx.showToast({
                title: '设置失败',
                icon: 'error',
              })
            }
          },
          fail(e){
            wx.showToast({
              title: '设置失败',
              icon: 'error',
            })
          }
        })
        break;
      }
      case 6: {
        // 修改营业时间
        startWorkTime = null;
        endWorkTime = null;
        this.setData({
          timePickerTitle: '请选择上班时间',
          showTimePicker: true
        })
        break;
      }
      case 1: 
      case 2: 
      case 3: 
      default: {
        wx.showModal({
          title: '提示',
          content: '当前版本暂不支持此功能！',
          showCancel: false,
          confirmText: '知道了',
          complete: (res) => {
          }
        });

        break;
      }
    }
  },

  _postWorkTime(){
    if(!startWorkTime){
      startWorkTime = this.data.timePickValue;
      this.setData({
        timePickerTitle: '请选择结束时间'
      })
    }else if(!endWorkTime){
      endWorkTime = this.data.timePickValue;
      // 时间设置到数据库
      let t1 = this._splitTimeString(startWorkTime);
      let t2 = this._splitTimeString(endWorkTime);
      var that = this;
      
      console.log('----这里将上下班时间发送到数据库------', startWorkTime, endWorkTime)
      this.setData({
        showTimePicker: false
      })
      wx.request({
        url: app.data.global_urls.getChangeWorkTimeUrl(),
        method: 'POST',
          header:{
            'Authorization': `Bearer ${app.data.loginData.token}`,
            'content-type': 'application/x-www-form-urlencoded',
          },
          data:{
            startHour: t1.hours,
            startMinute: t1.minutes,
            endHour: t2.hours,
            endMinute: t2.minutes,
          },
          success(res){
            if(res.data.status !== 10000){
              wx.showToast({
                title: '修改失败',
                icon: 'error'
              })
            }else{
              // 数据库修改成功后再修改本地
              that._setWorkTimeForAdmin(t1.hours, t1.minutes, t2.hours, t2.minutes);
            }
          },
          fail(e){
            wx.showToast({
              title: '修改失败',
              icon: 'error'
            })
          }
      })
    }else{
      
    }
  },

  onTimePickConfirm(e){
    const { value } = e.detail;
    const { mode } = this.data;

    console.log('confirm', value);

    this.setData({
      timePickValue: value
    });
    this._postWorkTime();
  },
  onTimePickColumnChange(e){},
  hideTimePicker(e){
    this.setData({
      showTimePicker: false
    })

  },

  _splitTimeString(timeString) {    
    const parts = timeString.split(':');    
    const hours = parseInt(parts[0], 10);    
    const minutes = parseInt(parts[1], 10);    
    return {hours, minutes};
 },
  
  jumpNav(e) {
    const status = e.detail.tabType;
    console.log('------jumpNav--------', e)
    wx.navigateTo({
      url: `/pages/order-all/order-all?status=${status}`
    });

    // if (status === 0) {
    //   wx.navigateTo({
    //     url: '/pages/order/after-service-list/index'
    //   });
    // } else {
    //   wx.navigateTo({
    //     url: `/pages/order/order-list/index?status=${status}`
    //   });
    // }
  },

  jumpAllOrder() {
    wx.navigateTo({
      url: '/pages/order-all/order-all'
    });
  },

  openMakePhone() {
    this.setData({
      showMakePhone: true
    });
  },

  closeMakePhone() {
    this.setData({
      showMakePhone: false
    });
  },

  // call() {
  //   wx.makePhoneCall({
  //     phoneNumber: this.data.customerServiceInfo.servicePhone,
  //   });
  // },
  bindWchatPhone() {
    console.log('绑定手机号');

    wx.openSetting({
      success (res) {
        console.log(res.authSetting)
        // res.authSetting = {
        //   "scope.userInfo": true,
        //   "scope.userLocation": true
        // }
      }
    })

    wx.authorize({
      scope: 'scope.userInfo',
      success () {
        // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
        console.log('同意授权')
      },
      fail(){
        console.log('授权失败')
      }
    });

    // wx.openSetting({
    //   success: (settingRes) => {
    //     if (settingRes.authSetting['scope.userInfo']) {
    //       console.log('用户已重新授权');
    //       // 再次调用获取用户信息的方法
    //       // this.getUserProfile();
    //     } else {
    //       console.log('用户仍未授权');
    //     }
    //   }
    // });

    new Promise((resolve, reject) => {
      wx.getUserInfo({
        // desc: '获取用户信息用于登录',
        withCredentials: true,
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err)
        }
      })
    }).then((res) => {
      console.log(res)
      var code = this.data.code;
      var token = this.data.token;
      var url = app.data.global_urls.getBindPhoneUrl();
      wx.request({
        url: url,
        method: 'POST',
        data: {
          code: code,
          encryptedData: res.encryptedData,
          iv: res.iv
        },
        header: {
          'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          // 处理手机号绑定结果
          console.log(res);
        }
      })

      return res;
    })
  },
  
  gotoUserEditPage() {
    var that = this;
    console.log(this.data.loginData)
    if(!this.data.loginData || !this.data.loginData.openid){
      // 
      wx.showToast({
        title: '正在登录...',
        icon: 'loading',
        duration: 30000,
        mask: true,
        complete(){
          console.log('toast 完成函数回调')
        },
      })
      app._userLogin(this._loginCallBack.bind(this), this._loginCallBack.bind(this));
    }
    //
  },

  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const {
      version,
      envVersion = __wxConfig
    } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
    console.log('获取小程序版本：', this.data.versionNo, versionInfo, __wxConfig)
  },

  getPhoneNumber (e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
  },

  testWxPay(){
    var that = this;
    new Promise((resolve, reject) => {
      wx.request({
        url: app.data.global_urls.getWxprepayIdUrl(),
        method: 'POST',
        header:{
          'Authorization': `Bearer ${this.data.loginData.token}`,
          'content-type': 'application/x-www-form-urlencoded'
        },
        data:{
          orderId: 18
        },
        success(res){
          if(10000 !== res.data.status){
            console.log("获取预支付失败1", res)
            app._needReLogin(that._loginCallBack, that._loginCallBack);
          }else{
            console.log("获取预支付成功", res.data.data)
            resolve(res.data.data);
          }
        },
        fail(e){
          app._needReLogin(that._loginCallBack, that._loginCallBack);
          console.log("获取预支付失败2", e)
        }
      })
    }).then((prepayArg) => {
      wx.requestPayment({
        timeStamp: prepayArg.timeStamp,
        nonceStr: prepayArg.nonceStr,
        package: prepayArg.packageVal,
        signType: prepayArg.signType,
        paySign: prepayArg.paySign,
        success (res) {
          console.log("支付成功", res)
         },
        fail (res) {
          console.log("支付失败", res)
         }
      })
    });

  },

  logout(){
    var that = this;

    wx.showModal({
      title: '警告',
      content: '确定退出登录吗？',
      cancelText: '否',
      confirmText: '是',
      complete: (res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          app.data.loginData = {
            userInfo: {
              avatarUrl: '',
              nickName: '请登录',
              phoneNumber: '',
              address: ''
            },
            token: '',
            openid: '',
          };
          that.setData({
            loginData:app.data.loginData
          });
          wx.removeStorage({
            key: 'key',
            success (res) {
              console.log(res)
            }
          })
        }
      }
    })
  },

  _checkLoginStatus(){
    if(!app.data.loginDone && !this.toastHasShow)
    this.toastHasShow = true;
  },

  onUnload(){
    clearInterval(this.data.monitorThreadId);
  }
});
